package com.youth.filter;

import com.google.gson.JsonObject;
import com.youth.commonutils.JwtUtils;
import com.youth.commonutils.UserDto;
import com.youth.commonutils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;


/*
 * 这是一个全局filter，那些请求可以访问，那些请求不可以访问，当你失败会输出什么值
 * 比如下面配置的带有 "/api/**"/auth/"**的就可以访问， "
 *            带有“/**"/"inner/**” 的就不可以访问
 * */

@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    @Autowired
    private RedisTemplate redisTemplate;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        System.out.println(path);

        //青年学习通api接口，校验用户必须登录:
        /*按如下格式进行路径判断，比如订单、收藏、发表评论都需要判断用户是否已经登录*/
        if (antPathMatcher.match("/api/**/auth/**", path)
                || antPathMatcher.match("/userservice/member/test", path)
                || antPathMatcher.match("userservice/course/collect/*", path)
//                || antPathMatcher.match("/api/**/auth/**", path)
//                || antPathMatcher.match("/api/**/auth/**", path)
//                || antPathMatcher.match("/api/**/auth/**", path)
        ) {
//            校验token，如果token有效则根据直接放行
            String token = request.getHeaders().get("token").get(0);
            boolean checkToken = JwtUtils.checkToken(token);
            if (checkToken) {       // 放行
                UserDto userDto = JwtUtils.getUserDtoByToken(token);
//                刷新token
                redisTemplate.opsForValue().set(userDto.getNickName(), token, 24, TimeUnit.HOURS);
            }
        }
        //内部服务接口，不允许外部访问
        if (antPathMatcher.match("/**/inner/**", path)) {
            ServerHttpResponse response = exchange.getResponse();
            return out(response);
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }

    private Mono<Void> out(ServerHttpResponse response) {
        JsonObject message = new JsonObject();
        message.addProperty("success", false);
        message.addProperty("code", 28004);
        message.addProperty("data", "鉴权失败");
        byte[] bits = message.toString().getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        //response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }
}
